#importing System files....
import sys
import os
import string
import errno
import optparse

#importing local files....
import dir_fxns
import compile_make_commands
import arg_check
import archive_generator

#-----------------------------------------------------------------------------

def automate_tasks(path,clean_option,exec_env):     
    os.chdir(path)
    print "Running \"git pull\" on %s system..." % exec_env
    sys.stdout.flush()
    retcode=dir_fxns.update_dir(path)
    if retcode.poll()!=0:
        print "----------------------------------------------\
----------------------------"
        print "Error occurred in updating the directory using the \
\"git pull\" command on %s system. Now checking whether SOURCE directory\
 exists in path specified or not and if it does, then compiling that code\
 only.." % exec_env
        print "----------------------------------------------\
----------------------------"
        sys.stdout.flush()
    else:
        print "\"git pull\" successfull on %s system." % exec_env
        sys.stdout.flush()
    dirs=dir_fxns.listdir_check(path)  #Checking the validity of the
                                       #path and getting the list of
                                       #directories present there if
                                       #path specified is correct....
    if dirs==-1001:
        print "\nError occured while listing the contents of directory of path\
 specified.... \nPlease check it...."
        print "Program exiting...."
        sys.stdout.flush()
        exit(1)
    dir_present=0    #This variable is to check whether the path
                     #specified contains the source directory inside
                     #it as well...
    
    #print dirs
    for dir_p in dirs:  #Taking all the directories and checking for the
                      #source directory inside the path specified.....
        if string.upper(dir_p)=="SOURCE":
            path_binaries=path+"/binaries"  #If source directory is
                                            #present, then create a
                                            #binaries directory where
                                            #the libraries will be
                                            #stored after compilation.
            dir_retcode=dir_fxns.mkdir_p(path_binaries)
            if dir_retcode!=0:
                print "----------------------------------------------\
----------------------------"
                print "Error!!!\nUnable to create\
 %s directory!!!" % path_binaries  #If unable to create directory when
                                   #it doesn't exist, then display the
                                   #error message....
                print "Exiting from the program. \
First correct the error and then re-execute the program......"
                print "-----------------------------------------------\
----------------------------"
                sys.stdout.flush()
                exit(1)
            
            path_logs=path+"/logs"
            dir_retcode=dir_fxns.mkdir_p(path_logs)
            if dir_retcode!=0:
                print "-------------------------------------------------\
-------------------------"
                print "Error!!!\nUnable to create %s directory!!!"\
 % path_logs    #If unable to create directory when it doesn't exist,
                #then display the error message....
                print "Exiting from the program. First correct the error and\
 then re-execute the program......"
                print "--------------------------------------------------\
------------------------"
                sys.stdout.flush()
                exit(1)
            
            code_path=path+"/"+dir_p
            code_dirs=dir_fxns.listdir_check(code_path) #Getting the
                                                        #list of all
                                                        #the
                                                        #directories
                                                        #present
                                                        #inside the
                                                        #source
                                                        #directory....
            if code_dirs==-1001:
                print "\nError occured while listing the contents of\
 directory of path specified.... \nPlease check it...."
                print "Program exiting...."
                sys.stdout.flush()
                exit(1)
            
            for code_dir in code_dirs: #Now taking each directory
                                       #present inside source
                                       #directory...
                curr_dir=code_path+"/"+code_dir
                os.chdir(curr_dir) #This leads to setting up of the
                                   #focus onto the code directory and
                                   #we can now run configure commands
                                   #in there....
                
                dir_retcode=dir_fxns.mkdir_p(path_binaries+"/"+code_dir) 
                #Creating a directory inside the binaries directory
                #with the name as same of the name of the code
                #directory....
                if dir_retcode!=0:
                    print "-----------------------------------------------\
---------------------------"
                    print "Error!!!\nUnable to create %s/%s directory!!!"\
 % (path_binaries,code_dir) #If unable to create directory when it
                            #doesn't exist, then display the error
                            #message....
                    print "Exiting from the program. First correct the error\
 and then re-execute the program......"
                    print "-----------------------------------------------\
---------------------------"
                    sys.stdout.flush()
                    exit(1)
                    
                dir_retcode=dir_fxns.mkdir_p(path_logs+"/"+code_dir)     
                #Creating a directory inside the logs directory with
                #the name as same of the name of the code
                #directory....
                if dir_retcode!=0:
                    print "------------------------------------------------\
--------------------------"
                    print "Error!!!\nUnable to create %s/%s directory!!!"\
% (path_logs,code_dir)   
                    #If unable to create directory when it doesn't
                    #exist, then display the error message....
                    print "Exiting from the program. First correct the error \
and then re-execute the program......"
                    print "------------------------------------------------\
--------------------------"
                    sys.stdout.flush()
                    exit(1)
                    
                if clean_option==True:
                    print "-------------------------------------------------\
-------------------------"
                    print "Make_dist_clean started on %s for %s directory" \
% (exec_env,code_dir)
                    print "--------------------------------------------------\
------------------------\n"
                    sys.stdout.flush()
                    retcode=compile_make_commands.clean_dist()
                    if retcode.returncode!=0:
                        print "----------------------------------------------\
----------------------------"
                        print "Error occured while running \"make dist \
clean\" command on %s computer for %s directory" % (exec_env,code_dir)
                        print "---------------------------------------------\
-----------------------------"
                        sys.stdout.flush()

                print 'Configure started on %s computer for %s' \
% (exec_env,code_dir)
                sys.stdout.flush()
                retcode=compile_make_commands.configure_with_prefix(
                                    path_binaries,
                                    code_dir,
                                    path_logs,
                                    exec_env)
                if retcode!=0:
                    print "-----------------------------------------------\
---------------------------"
                    print "Error occured while running configure command \
on %s for %s directory" % (exec_env,code_dir)
                    print "Please check the configure.log file generated \
for %s directory for the error information" % code_dir
                    print "Stopping the code_building process for %s system" \
% exec_env
                    print "------------------------------------------------\
--------------------------"
                    sys.stdout.flush()
                    exit(1)
                else:
                    print 'Configure \"success\" on %s computer for %s' \
% (exec_env,code_dir)
                    sys.stdout.flush()


                print 'Make started on %s computer for %s'\
 % (exec_env,code_dir)
                sys.stdout.flush()
                ret_make=compile_make_commands.make(
                                    code_dir,
                                    path_logs,
                                    exec_env)
                if ret_make!=0:
                    print "-----------------------------------------------\
---------------------------"
                    print "Error occurred while running make command on %s \
for %s directory" % (exec_env,code_dir)
                    print "Please check the make.log file generated for %s \
directory for the error information" % code_dir
                    print "Stopping the code_building process for %s \
system" % exec_env
                    print "------------------------------------------------\
--------------------------"
                    sys.stdout.flush()
                    exit(1)
                else:
                    print 'Make \"success\" on %s computer for %s' \
% (exec_env,code_dir)
                    sys.stdout.flush()


                print 'Make_install started on %s computer for %s'\
 % (exec_env,code_dir)
                sys.stdout.flush()
                ret_make_install=compile_make_commands.make_install(
                                                        code_dir,
                                                        path_logs,
                                                        exec_env)
                if ret_make_install!=0:
                    print "-----------------------------------------------\
---------------------------"
                    print "Error occurred while running make_install command\
 on %s for %s directory" % (exec_env,code_dir)
                    print "Please check the make_install.log file generated \
for %s directory for the error information" % code_dir
                    print "Stopping the code_building process for %s system"\
 % exec_env
                    print "------------------------------------------------\
--------------------------"
                    sys.stdout.flush()
                    exit(1)
                else:
                    print 'Make_Install \"success\" on %s computer for %s'\
 % (exec_env,code_dir)
                    sys.stdout.flush()
            dir_present=1                      
            #setting up the variable to indicate that source directory
            #was present in the path specified....
            print "-------------------------------------------------------\
------------------------"
            print "\nCode building process finished successfully for %s \
system....." % exec_env
            print "Log files can be seen for configure, make and make_install \
commands in %s/logs directory\n" % path
            print "-------------------------------------------------------\
------------------------"
            sys.stdout.flush()
            break      #Exiting after processing the source
                       #directory....
    if dir_present==0:   #Checking whether the directory "source" was
                         #present or not......
        print "-----------------------------------------------------------\
 --------------------"
        print "\n\tNo source directory found in the path(%s) provided......"\
 % path
        print "\tPlease check the path value.... \n\tIt should contain \
source directory inside it....."
        print "------------------------------------------------------------\
-------------------"
        sys.stdout.flush()
        return -1
    else:
        copy_status=archive_generator.copy_files(path+"/binaries",exec_env)
    return 0

#This __main__ method is only for the "remote calling" or when
#directly running this file to compile. So the local compilation which
#is started by initiator.py will not enter in this method but in the
#above method.  This is called only when we execute this file directly
#with the parameters.
#-----------------------------------------------------------------------------
if __name__=="__main__":
    parser=optparse.OptionParser()
    parser.add_option("-p","--path",
                      dest="path",
                      type="string",
                      help="This takes path of vPth-dissector code directory which is checked out from the vPath-dissector.git repository..",
                      action="store")
    
    parser.add_option("-c","--clean",
                      dest="clean",
                      default=False,
                      help="This flag tells whether you want to do make_dist_clean on the code directory or not. If you specify it, then it will do the clean option before compiling the code.",
                      action="store_true")
    
    (options, args)=parser.parse_args()   
    
    path=options.path
    make_clean_option=options.clean
    
    #retcode=arg_check.input_check(len(sys.argv))
    #if retcode==-999:
    #    exit(1)
    #elif retcode==0:
    #    path=sys.argv[1]
    #    make_clean_option=sys.argv[2]
        
    path_exists=arg_check.path_check(path)
    if path_exists==False:
        print "Wrong path %s specified...... Please check the first \
argument......" % path
        print "Program exiting now........"
        exit(1)
        
    #retcode=arg_check.arg_yes_no_check(make_clean_option)
    #if retcode==-998:
    #    print "Second argument to file specified incorrectly!!! \
#It should be either \"Yes\" or \"No\". Please Check it...."
    #    print "Program exiting....... "
    #    exit(1)

    status=automate_tasks(path,make_clean_option,"x64") 
        #"x64" here becaue this python file is executed remotely on
        #x64 system..... When executed locally, main is not called....

#-----------------------------------------------------------------------------
